package com.qf.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.air.entity.Air;
import com.qf.air.mapper.AirMapper;
import com.qf.air.service.AirService;
import com.qf.air.service.ElasticsearchService;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.shard.IndexShardRecoveringException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * ES同步数据
 * @author zjw
 */
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = {
        "classpath:applicationContext-jedis.xml" ,
        "classpath:applicationContext-mybatis.xml",
        "classpath:applicationContext-service.xml",
        "classpath:applicationContext-tx.xml"
})
public class ElasticsearchSyncData {

    @Autowired
    private AirMapper airMapper;

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Test
    public void sync() throws IOException {
        List<Air> list = airMapper.findByDistrictId(null, null, null, null);
        ObjectMapper objectMapper = new ObjectMapper();
        List<IndexRequest> requests = new ArrayList<>();
        for (Air air : list) {
            //1. IndexRequest
            IndexRequest request = new IndexRequest();
            //2. 索引，id，文档
            request.index("air");
            request.id(air.getId() + "");
            request.source(objectMapper.writeValueAsString(air), XContentType.JSON);

            //3. requests执行add
            requests.add(request);
        }

        // 调用service添加
        elasticsearchService.bulk(requests.toArray(new IndexRequest[]{}));
    }


}
